package com.wstuo.common.tools.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.tools.dto.SMSMessageDTO;
import com.wstuo.common.tools.service.ISMSRecordService;

/**
 * 盤志短信
 * @author QXY
 *
 */
public class PanZhiSMSHelper implements ISMSSender{
	
	private static final Logger LOGGER = Logger.getLogger(PanZhiSMSHelper.class ); 
	@Autowired
	private ISMSRecordService smsRecordService;
	
	
	public String doSend(String postUrl,String action, String phoneNumbers, String message) {
		
		if(action!=null){
			postUrl=postUrl.replace("{action}", action);
		}
		
		if(phoneNumbers!=null && message!=null){
			postUrl=postUrl.replace("{msg}", message)
			.replace("{phoneNumbers}", phoneNumbers);
		}

		String result = "";
		
		URL url = null; 
		URLConnection conn=null;
		OutputStream out =null;
		InputStream stream = null;
		try {
			url = new URL(postUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			out = conn.getOutputStream();
			out.write(postUrl.getBytes("GBK"));  //字符集须为GBK  
			
			stream = conn.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(stream));
			String line = "";
			
			while((line = in.readLine())!= null){//读取结果
				result = result + line;
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		} finally {
			try {
				if(out!=null){
					out.flush();
					out.close();
				}
				if(stream!=null){
					stream.close();
				}
				
			} catch (IOException e) {
				LOGGER.error(e);
			}
			
		}
		
		return result;
	}
	
	

	public SMSMessageDTO SendSms(String postUrl,String mobile, String content, boolean isSystem,
			boolean saveHistory) {
		
		
		
		//初始化数据
		SMSMessageDTO dto=new SMSMessageDTO();
		dto.setSendCount(0);
		String [] mobilePath=ContentSpliter.getMobileArrFromString(mobile);
		String [] contentPath=ContentSpliter.getMsgArrFromString(content);
		
		
		//循环发送
		for(int i=0;i<mobilePath.length;i++){
			
			if(!"".equals(mobilePath[i].trim())){
			
				for(int j=0;j<contentPath.length;j++){
					
					String returnMessage=switchMessage(doSend(postUrl,"send",mobilePath[i].trim(),contentPath[j].trim()));
					
					dto.setStateMsg(returnMessage);
					
					if(returnMessage.indexOf("发送成功")==-1){//存在错误，返回
						return dto;
					}
					
					dto.setSendCount(dto.getSendCount()+1);
					if(saveHistory){//保存历史记录
						smsRecordService.saveSMSHistory(mobilePath[i].trim(),contentPath[j].trim(),isSystem);
					}
				}
			}
		}
		return dto;
	}
	


	public SMSMessageDTO queryMoney(String postUrl) {
		
		String msg=doSend(postUrl,"check",null,null).replace("nums=", "");
		SMSMessageDTO dto=new SMSMessageDTO();
		dto.setTotalMoney(msg+"_tiao");
		return dto;
		
	}

	
	public Boolean testConnection(String postUrl) {
		boolean result = false;
		if( !( postUrl.indexOf("orgid=&")!=-1 || postUrl.indexOf("orgid=null")!=-1 ) ){		
			String busy=doSend(postUrl,"busytest",null,null);
			if(busy.equals("1")){//正常
				result = true;
			}
		}
		
		return result;
	}
	
	
	/**
	 * 根据返回字符串匹配信息。
	 * @param msg
	 * @return
	 */
	private static String switchMessage(String msg){
		String result = "";
		String state=msg.substring(0,msg.indexOf("&")).replace("state=", "");
		Integer stateNo=Integer.parseInt(state);
		
		switch(stateNo){
			case 0: result = "短信发送成功！";break;
			case 100: result = "定时成功！";break;
			case -1: result = "发送失败";break;
			case -2: result = "您的帐号有误，请检查！";break;
			case -3: result = "您的密码有误，请检查！";break;
			case -4: result = "您的机构有误，请检查！";break;
			case -5: result = "短信内容不合法，请确认。";break;
			case -6: result = "手机号码不合法，请确认。";break;
			case -7: result = "用户被临时禁用，请联系提供商。";break;
			case -8: result = "您的账户余额不足，请及时充值！";break;
			case -9: result = "网路出现异常，请稍候再试。";break;
			case -10: result = "非接口用户";break;
			case -11: result = "认证key错误";break;
			case -12: result = "SP发送超时";break;
			case -15: result = "帐号被禁止";break;
			case -20: result = "无可用的通道";break;
			case -30: result = "更新批号错误";break;
			case -31: result = "号码中包含拒绝发送的号码";break;
			case -32: result = "定时参数不合法 ";break;
			case -100: result = "非法调用";break;
			default: result = "未知错误";
		}

		return result;
	}
}
